import serviceType from "../../enum/service-type";
import { getDataSet, getEventParam } from "../../utils/util";
import Category from "../../model/category";

const moment = require("../../lib/moment")

// components/service-form/service-form.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    form:Object
  },

  // observers:{
  //   form:function(newValue){
  //     // console.log(newValue);
  //     if(!newValue){
  //       return;
  //     }
  //     this._init();
  //   }
  // },

  /**
   * 组件的初始数据
   */
  data: {
    typeList:[
      {
        id:serviceType.PROVIDE,
        name:'提供服务'
      } ,
      {
        id:serviceType.SEEK,
        name:'找服务'
      }
    ],
    categoryList:[],
    categoryPickerIndex:null,
    typePickerIndex:null,
    formData: {
        type: null,
        title: '',
        category_id: null,
        cover_image_id: null,
        description: '',
        designated_place: false,
        begin_date: '',
        end_date: '',
        price: ''
    },
    rules:[
      {
        name: 'type',
        rules: { required: true, message: '请指定服务类型' },
    },
    {
        name: 'title',
        rules: [
            { required: true, message: '服务标题内容不能为空' },
            { minlength: 5, message: '服务描述内容不能少于 5 个字' },
        ],
    },
    {
        name: 'category_id',
        rules: { required: true, message: '未指定服务所属分类' },
    },
    {
        name: 'cover_image_id',
        rules: { required: true, message: '请上传封面图' },
    },
    {
        name: 'description',
        rules: [
            { required: true, message: '服务描述不能为空' },
            { minlength: 20, message: '服务描述内容不能少于 20 个字' },
        ],
    },
    {
        name: 'begin_date',
        rules: [
            { required: true, message: '请指定服务有效日期开始时间' },
        ],
    },
    {
        name: 'end_date',
        rules: [
            { required: true, message: '请指定服务有效日期结束时间' },
            {
                validator: function (rule, value, param, models) {
                    if (moment(value).isSame(models.begin_date) || moment(value).isAfter(models.begin_date)) {
                        return null
                    }
                    return '结束时间必须大于开始时间'
                }
            }
        ],

    },
    {
        name: 'price',
        rules: [
            { required: true, message: '请指定服务价格' },
            {
                validator: function (rule, value, param, models) {
                    const pattern = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/
                    const isNum = pattern.test(value);

                    if (isNum) {
                        return null
                    }
                    return '价格必须是数字'
                }
            },
            { min: 1, message: '天下没有免费的午餐' },
        ],
    },
    ],
    error:null,
    resetForm:true
  },
  pageLifetimes:{
    show(){
      if(this.data.resetForm){
        this._init(this.data.form);
      }
      this.data.resetForm = true
    },
    hide(){
      if(this.data.resetForm){
        this.setData({
          showFrom:false
        })
      } 
    }
  },
  // lifetimes:{ 
  //   attached(){  
  //     this._init();
  //   }
  // },

  /**
   * 组件的方法列表
   */
  methods: {
    async _init(){
      // for(let i=0;i<this.data.typeList.length;i++){
      //   if(this.form.type === this.data.typeList[i].id){
      //         this.setData({
      //           typePickerIndex:i
      //         })
      //         return 
      //   }
      // }
 
      const typePickerIndex = this.data.typeList.findIndex(item=>{
        return this.data.form.type === item.id
      })

      const categoryList = await Category.getCagtegoryList(); 
      const categoryIndex = categoryList.findIndex(item=>{
        return this.data.form.category_id === item.id
      })

      let form = this.data.form;
      this.setData({
          showFrom:true,
          typePickerIndex: typePickerIndex !== -1 ? typePickerIndex : null,  
          categoryIndex: categoryIndex !== -1 ? categoryIndex : null,
          categoryList,
          files: form.cover_image ? [form.cover_image] : [],
          formData: {
            type: form.type,
            title: form.title,
            category_id: form.category_id,
            cover_image_id: form.cover_image ? form.cover_image.id : null,
            description: form.description,
            designated_place: form.designated_place,
            begin_date: form.begin_date,
            end_date: form.end_date,
            price: form.price
          } 
      })

    },

    submit(){
      this.selectComponent('#form').validate(async (valid, errors) => {
        if (!valid) {
            const errMsg = errors.map(error => error.message)
            this.setData({
                error: errMsg.join('；'),
            })
            return
        }
        this.triggerEvent('submit', { formData: this.data.formData })
    })
    },

    handleTypeChange(e){
      // console.log(e);
      const index = getEventParam(e,'value')
      // console.log(index);
      this.setData({
        typePickerIndex:index,
        ['fromData.type'] : this.data.typeList[index].id
      })
    },

    handleInput(e){
      // console.log(e);
      const value = getEventParam(e,'value');
      const field = getDataSet(e,'field');
      this.setData({
        [`formData.${field}`]:value
      }) 
    },

    handlCategoryChange(e){
      const categoryPickerIndex = getEventParam(e,'value'); 
      this.setData({
        categoryPickerIndex,
        [`formData.category_id`]:this.data.categoryList[categoryPickerIndex].id
      })
    },

    handleSwithChange(e){
      const res = getEventParam(e,'value');
      this.setData({
        [`formData.designated_place`]:res
      }) 
    },

    handleBeginDateChange(e){
      const beginData = getEventParam(e,'value');
      this.setData({
        [`formData.begin_date`]:beginData
      }) 
    },
    handleEndDateChange(e){
      const endData = getEventParam(e,'value'); 
      this.setData({
        [`formData.end_date`]:endData
      }) 
    },

    handleHidePage() {
      this.data.resetForm = false
  },

  handleUploadSuccess: function (event) {
      const files = event.detail.files
      this.setData({
          'formData.cover_image_id': files[0].id
      })
  }

  }
})
